<template>
  <view class="content">
    <view class="containerBase">
      <live-pusher
        id="livePusher1"
        :url="livePusherUrl"
        :debug="pushConfig.showLog"
        :muted="pushConfig.muted"
        :remote-mirror="pushConfig.isMirror"
        :local-mirror="pushConfig.isMirror ? 'enable' : 'disable'"
        :beauty="pushConfig.isBeauty"
        :whiteness="pushConfig.isWhiteness"
        :orientation="pushConfig.orientation"
        :audio-reverb-type="pushConfig.audioReverbType"
        waiting-image="https://storage.zego.im/downloads/pause_publish.png"
        v-if="isPusherShow"
        mode="SD"
        min-bitrate="800"
        max-bitrate="1500"
        @statechange="statechange"
        @netstatus="netstatus"
        @error="pusherError"
      ></live-pusher>
      <live-player
        v-for="streamItem in livePlayerList"
        :id="streamItem.streamID"
        :key="streamItem.streamID"
        :src="streamItem.url"
        autoplay
        @statechange="playStatechange"
        @netstatus="playNetstatus"
        @error="playError"
      ></live-player>
    </view>
    <view class="index-container">
      <view class="input-container">
        <input v-model="roomID" placeholder="请输入房间 ID" placeholder-style="color: #b3b3b3; font-size: 14px;" class="room-input" />
        <text class="tip"></text>
      </view>
      <view class="button-container">
        <button @click="openRoom(1)" class="util-btn">加入房间(推流)</button>
        <button @click="openRoom(0)" class="util-btn">加入房间(不推流)</button>
        <button @click="switchCamera" class="util-btn">切换相机({{ pushConfig.frontCamera ? "前" : "后" }})</button>
        <button @click="enableMute" class="util-btn">{{ pushConfig.muted ? "打开" : "关闭" }}麦克风</button>
        <button @click="setMirror" class="util-btn">{{ pushConfig.isMirror ? "关闭" : "打开" }}镜像</button>
        <button @click="setBeauty" class="util-btn">{{ pushConfig.isBeauty ? "关闭" : "打开" }}美颜</button>
        <button @click="setWhiteness" class="util-btn">{{ pushConfig.isWhiteness ? "关闭" : "打开" }}美白</button>
        <button @click="toggleOrientation" class="util-btn">画面方向</button>
        <button @click="showLog" class="util-btn">{{ pushConfig.showLog ? "关闭" : "打开" }}日志</button>
        <!-- <button @click="logout">退出房间</button> -->
      </view>
    </view>
    <view class="settings">
      <button v-if="isSettingShow" open-type="openSetting" @openSetting="settingCallback">
        授权使用摄像头和麦克风
      </button>
    </view>
  </view>
</template>

<script>
import { CommonExpress } from "../../utils/wxmini/common"

export default {
  data() {
    return {
      commonExpress: null,
      roomID: "126",
      livePusherctx: "",
      livePusherUrl: "",
      isPusherShow: false,
      isSettingShow: false,
      livePlayerList: [],
      pushConfig: {
        // 推流配置项
        mode: "RTC",
        minBitrate: 200, // 最小视频编码码率
        maxBitrate: 500, // 最大视频编码码率
        isBeauty: 6, // 美颜程度，取值范围 [0,9]
        isWhiteness: 6, // 美白程度，取值范围 [0,9]
        muted: false, // 推流是否静音
        showLog: false, // 是否显示 log
        frontCamera: true, // 前后置摄像头，false 表示后置
        enableCamera: true, // 是否开启摄像头
        isMirror: false, // 画面是否镜像
        orientation: "vertical",
        audioReverbType: 0
      }
    }
  },

  methods: {
    async openRoom(type) {
      // 0 不推流 1 推流
      await this.commonExpress.login(this.roomID)
      if (type === 1) {
        // 获取到推流地址 推流流地址
        const { url } = await this.commonExpress.getPublishStream()
        this.livePusherUrl = url
        this.isPusherShow = true
        this.$nextTick(async () => {
          // // 创建 pusher上下文 ， 一般建议在需要推流的时候，再创建上下文，以及 stateChange监听 和 netChange 监听
          this.livePusherctx = uni.createLivePusherContext("livePusher1", this)
          // this.livePusherctx.url = url  //注释掉试试
          //  开始推流，同时开启摄像头预览
          const res = await this.livePusherctx.start()
        })
      }
    },

    settingCallback(e) {
      console.log("mytag settingCallback e", e)
      if (e.errMsg.includes("ok")) {
        this.isSettingShow = false
      }
    },

    async logout() {
      // 停止推流
      if (this.livePusherctx && this.livePusherUrl) {
        this.commonExpress.zegoApi.stopPublishingStream(this.livePusherUrl)
        this.livePusherctx.stop()
      }

      // 停止拉流
      this.livePlayerList.forEach((item) => {
        this.commonExpress.zegoApi.stopPlayingStream(item.streamID)
      })
      this.livePlayerList = []

      // 退出房间服务
      const res = await this.commonExpress.zegoApi.logoutRoom()
      uni.navigateBack()
    },

    async initCommon() {
      this.commonExpress = new CommonExpress()
      const checkRes = await this.commonExpress.checkSystemRequirements()
      this.livePlayerList = this.commonExpress.livePlayerList // 与 commonExpress中的 livePlayerList进行深拷贝。
      if (!checkRes) this.isSettingShow = true
    },

    switchCamera() {
      this.pushConfig.frontCamera = !this.pushConfig.frontCamera
      this.livePusherctx && this.livePusherctx.switchCamera()
    },
    enableMute() {
      this.pushConfig.muted = !this.pushConfig.muted
    },
    setMirror() {
      this.pushConfig.isMirror = !this.pushConfig.isMirror
    },
    setBeauty() {
      this.pushConfig.isBeauty = this.pushConfig.isBeauty === 0 ? 6 : 0
    },
    setWhiteness() {
      this.pushConfig.isWhiteness = this.pushConfig.isWhiteness === 0 ? 6 : 0
    },
    toggleOrientation() {
      this.pushConfig.orientation = this.pushConfig.orientation === "vertical" ? "horizontal" : "vertical"
    },
    showLog() {
      this.pushConfig.showLog = !this.pushConfig.showLog
    },

    // live-pusher 推流状态回调
    statechange(e) {
      console.log("mytag statechange this.commonExpress.streamID, e", this.commonExpress.streamID, e)
      try {
        if (e.detail.code === -1307) {
          uni.showToast({
            icon: "none",
            title: "网络断连，且经多次重连抢救无效，更多重试请自行重启推流"
          })
        }
        this.commonExpress.zegoApi.updatePlayerState(this.commonExpress.streamID, e)
      } catch (error) {
        console.log("mytag state ", error)
      }
    },

    // live-pusher 推流网络状态通知
    netstatus(e) {
      try {
        console.warn("mytag netstatus", this.commonExpress.streamID, e)
        this.commonExpress.zegoApi.updatePlayerNetStatus(this.commonExpress.streamID, e)
      } catch (error) {
        console.log("mytag netState ", error)
      }
    },

    // live-pusher 错误
    pusherError(e) {
      console.warn("mytag pusherError", e)
    },

    // live-player 拉流状态回调
    playStatechange(e) {
      console.log("mytag player playStatechange e", e.currentTarget.id, e)
      if (e.detail.code === -1307) {
        uni.showToast({
          icon: "none",
          title: "网络断连，且经多次重连抢救无效，更多重试请自行重启推流"
        })
      }
      this.commonExpress.zegoApi.updatePlayerState(e.currentTarget.id, e)
    },

    // live-player 拉流网络状态通知
    playNetstatus(e) {
      console.log("mytag player playNetstatus", e.currentTarget.id, e)
      this.commonExpress.zegoApi.updatePlayerNetStatus(e.currentTarget.id, e)
    },

    // live-player 错误
    playError(e) {
      console.warn("mytag player pusherError", e)
    }
  },

  async mounted() {
    this.initCommon()
  }
}
</script>

<style>
.containerBase {
  height: 73vh;
  max-height: 500px;
  padding: 10rpx;
}

live-pusher,
live-player {
  width: 45vw;
  height: 45vw;
  max-width: 200px;
  max-height: 200px;
  margin: 5rpx;
}

.index-container {
  border-top: 1px slategrey solid;
}
.input-container {
  text-align: center;
}
.button-container {
  border-top: 1px slategrey solid;
}
.room-input {
  height: 80rpx;
  border-bottom: 1px solid rgba(13, 112, 255, 0.5);
}
button[type="primary"] {
  background-color: red;
}

.roomBtn {
  display: inline-block;
  width: 48vw;
  margin: 7rpx;
  background: rgba(13, 112, 255, 0.5);
  color: #fff;
}

.util-btn {
  display: inline-block;
  margin: 1vw;
  font-size: 20rpx;
  background: rgba(13, 112, 255, 0.5);
  color: #fff;
}
</style>
